package cn.com.czpb.client.module.news.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;

import cn.com.czpb.client.R;
import cn.com.czpb.client.api.InterfaceJsonfile;
import cn.com.czpb.client.app.ToolBarActivityWhite;
import cn.com.czpb.client.custorm.smartrefreshalayout.ClassHeader_other;
import cn.com.czpb.client.model.news.ComResultEntity;
import cn.com.czpb.client.model.news.CommBean;
import cn.com.czpb.client.model.news.CommEntity;
import cn.com.czpb.client.module.news.adapter.NewsCommentExpandAdapter;
import cn.com.czpb.client.module.news.dialog.ReplyDialog;
import cn.com.czpb.client.module.personal.acticity.LoginActivity;
import cn.com.czpb.client.net.Factory;
import cn.com.czpb.client.utils.ActionbarUtils;
import cn.com.czpb.client.utils.DeviceUtils;
import cn.com.czpb.client.utils.LogUtils;
import cn.com.czpb.client.utils.ParamUtils;
import cn.com.czpb.client.utils.TUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class CommentNewActivity extends ToolBarActivityWhite implements
        ExpandableListView.OnGroupClickListener, OnRefreshListener,
        ExpandableListView.OnLongClickListener, ExpandableListView.OnChildClickListener
        , NewsCommentExpandAdapter.onViewClick {

    public static final String PRAISE="PRAISE.COMMONT";

    @BindView(R.id.swipe_layout)
    SmartRefreshLayout swipe_layout;
    @BindView(R.id.expand_common)
    ExpandableListView expandableListView;
    private List<CommBean> list;
    private Map<String, List<CommBean.ChildrenEntity>> list_child;
    NewsCommentExpandAdapter adapter;
    @BindView(R.id.img_back_id)
    ImageView img_back_id;
    @BindView(R.id.back_toolbar)
    TextView back_toolbar;
    private int Page = 1;
    private static final int PageSize = 15;
    private boolean mFlagRefresh = true;
    private String type;
    private String newstype;
    private String nid;
    private String newsid;
    int position;
    LoginQuitBR br;

    @Override
    public int setMyContentView() {
        return R.layout.activity_common;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //状态栏字体颜色设置成深色
        ActionbarUtils.setMeizuStatusBarDarkIcon(activity, true);
        ActionbarUtils.setMiuiStatusBarDarkMode(activity, true);
        init();
        initBroadCast();
        settitleBg();
        img_back_id.setImageResource(R.drawable.black_back);
        back_toolbar.setTextColor(getResources().getColor(R.color.color_1a1a1a));
    }

    private void initBroadCast() {
        br = new LoginQuitBR();
        IntentFilter filter = new IntentFilter();
        filter.addAction(PRAISE);
        activity.registerReceiver(br, filter);
    }

    private void init() {
        nid = getIntent().getStringExtra("nid");
        newsid = getIntent().getStringExtra("newsid");
        type = getIntent().getStringExtra("type");
        newstype = getIntent().getStringExtra("newstype");
        LogUtils.e("nid--" + nid + "--" + newsid + "--" + type + "--" + newstype);
        list = new ArrayList<>();
        list_child = new HashMap<>();
        adapter = new NewsCommentExpandAdapter(list, list_child, activity, nid, type, this);
        initList();
        expandableListView.setAdapter(adapter);

        expandableListView.setOnChildClickListener(this);
        expandableListView.setOnGroupClickListener(this);


        swipe_layout.setRefreshHeader(new ClassHeader_other(this));
        expandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView expandableListView, View view, int i, long l) {
                return true;
            }
        });
        swipe_layout.setOnRefreshListener(this);
        expandableListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int scrollState) {
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
//                    position = expandableListView.getScrollX();
                    position = expandableListView.getScrollY();
                }
            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {

            }
        });
    }

    private void initList() {

        Map<String, String> map = new HashMap<>();
        map.put("nid", newsid);
        map.put("type", type);
        map.put("Page", Page + "");
        map.put("PageSize", PageSize + "");
        map.put("siteid", InterfaceJsonfile.SITEID);
//        map.put("deivce", DeviceUtils.getMyUUID(activity));
        if (spu.getUser() != null) {
            map.put("uid", spu.getUser().getUid());
        } else {
            map.put("device", DeviceUtils.getMyUUID(activity));
        }
        LogUtils.e("nid--"+map.get("deivce")+newsid+" "+type+" "+Page+" "+PageSize+" ");
        Factory.provideHttpService().AllNewsComment(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<CommEntity, Boolean>() {
                    @Override
                    public Boolean call(CommEntity commEntity) {
                        return true;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<CommEntity>() {
                    @Override
                    public void call(CommEntity commEntity) {
                        disMissDialog();
                        if (mFlagRefresh) {
                            swipe_layout.finishRefresh();
                        }

                        if (commEntity.code.equals("200")) {


                            setListData(commEntity.data);
                            for (CommBean commBean : commEntity.data) {
                                list_child.put(commBean.getCid(), commBean.getChildren());
                            }

                            adapter.notifyDataSetChanged();
                            for (int i = 0; i < list.size(); i++) {
                                expandableListView.expandGroup(i);
                            }
                        } else {
                            TUtils.toast(commEntity.msg);
                        }
                    }
                });
    }

    public void setListData(List<CommBean> list1) {
        if (mFlagRefresh) {
            list.clear();
            list.addAll(list1);
            adapter.notifyDataSetChanged();
        } else {
            list.addAll(list1);
            adapter.notifyDataSetChanged();
        }

    }


//    public void onItemChildClick(BaseQuickAdapter adapter1, View view, int position) {
//
//        final CommBean commBean = (CommBean) adapter1.getItem(position);
//        final ReplyDialog dialog = new ReplyDialog(activity, R.style.ChangeNamedialog, new ReplyDialog.InputListener() {
//            @Override
//            public void inputstr(String string) {
//                showDialog();
//                sendComment(string, commBean.getCid());
//                LogUtils.e("cid--"+commBean.getCid());
//                swipe_layout.setFreshResult(ISwipe.FreshStatus.SUCCESS);
//                mFlagRefresh = true;
//                list.clear();
//                initList();
//                adapter.notifyDataSetChanged();
//            }
//        });
//        dialog.show();
//    }

    private void sendComment(String content, String cid) {

        Map<String, String> map = new HashMap<>();
        map.put("nid", nid);
        map.put("uid", spu.getUser().getUid());
        map.put("type", newstype);
        map.put("title", nid);
        map.put("content", content);
        map.put("cid", cid);
        map.put("json_url", "fsdfsdfsfs");//随便传一个
        map.put("siteid", InterfaceJsonfile.SITEID);
        Factory.provideHttpService()
                .newsComment(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<ComResultEntity, Boolean>() {
                    @Override
                    public Boolean call(ComResultEntity entity) {
                        LogUtils.i("200-->" + entity.code);
                        if ("200".equals(entity.code)) {
                            LogUtils.i("200-->成功");
                            return true;
                        }
                        LogUtils.i("200失败");
                        return false;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<ComResultEntity>() {
                    @Override
                    public void call(ComResultEntity entity) {

                        if ("200".equals(entity.code)) {
                            TUtils.toast(entity.msg);
                        } else {
                            TUtils.toast(entity.msg);
                        }
                        expandableListView.scrollTo(0,position);
//                            setData();
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        TUtils.toast("评论失败");

                    }
                });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(br);
    }


    @Override
    public boolean onLongClick(View view) {
        return false;
    }

    @Override
    public boolean onChildClick(ExpandableListView expandableListView, View view, int i, int i1, long l) {


        try {
            if(spu.getUser()!=null){
                final CommBean commBean = list.get(i);
                final CommBean.ChildrenEntity obj = commBean.getChildren().get(i1);
                final ReplyDialog dialog = new ReplyDialog(activity, R.style.ChangeNamedialog, obj.getNickname(), new ReplyDialog.InputListener() {
                    @Override
                    public void inputstr(String string) {
                        showDialog();
                        sendComment("回复 " + obj.getNickname() + " :" + string, obj.getCid());
                        LogUtils.e("cid--" + obj.getCid());
                        mFlagRefresh = true;
                        list.clear();
                        initList();
                        adapter.notifyDataSetChanged();
                    }
                });
                dialog.show();
            }else {
                Intent intent = new Intent(activity, LoginActivity.class);
                activity.startActivity(intent);
                TUtils.toast("请先登录");

            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return true;

    }

    @Override
    public boolean onGroupClick(ExpandableListView expandableListView, View view, int i, long l) {
        final CommBean commBean = list.get(i);
        final ReplyDialog dialog = new ReplyDialog(activity, R.style.ChangeNamedialog, new ReplyDialog.InputListener() {
            @Override
            public void inputstr(String string) {
                showDialog();
                sendComment(string, commBean.getCid());
                LogUtils.e("cid--" + commBean.getCid());
                swipe_layout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mFlagRefresh = true;
                        list.clear();
                        initList();

                        adapter.notifyDataSetChanged();
                    }
                }, 2000);

            }
        });

        dialog.show();
        return true;
    }

    @Override
    public void OnClicker(final int i) {


        if (spu.getUser()!=null){
            final CommBean commBean = list.get(i);
            final ReplyDialog dialog = new ReplyDialog(activity, R.style.ChangeNamedialog, commBean.getNickname(), new ReplyDialog.InputListener() {
                @Override
                public void inputstr(String string) {
                    showDialog();
                    sendComment(string, commBean.getCid());
                    LogUtils.e("cid--" + commBean.getCid());
                    swipe_layout.getLayout().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mFlagRefresh = true;
                            list.clear();
                            initList();

                            adapter.notifyDataSetChanged();
                        }
                    }, 2000);


                }
            });
            dialog.show();

        }else {
            Intent intent = new Intent(activity, LoginActivity.class);
            activity.startActivity(intent);
            TUtils.toast("请先登录");
        }


    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        Page = 1;
        mFlagRefresh = true;
        initList();
    }
    public class LoginQuitBR extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(CommentNewActivity.PRAISE)) {
                adapter.notifyDataSetChanged();
            }
        }
    }

}
